package com.islewars.server;

import java.util.Date;
import java.util.List;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.islewars.client.dto.ChatLineDto;
import com.islewars.client.dto.GameDto;
import com.islewars.client.dto.MountainDto;
import com.islewars.client.dto.PlayerDto;
import com.islewars.client.service.GameService;

@SuppressWarnings("serial")
public class GameServiceImpl extends RemoteServiceServlet implements GameService {
	public GameServiceImpl() {
	}

	@Override
	public boolean login(String username) {
		StaticData.players.add(username);
		return true;
	}

	@Override
	public List<String> getPlayers() {
		return StaticData.players;
	}

	@Override
	public void say(String player, String text) {
		StaticData.chat.add(new ChatLineDto(new Date(), player, text));
	}

	@Override
	public List<ChatLineDto> getChat() {
		return StaticData.chat;
	}

	@Override
	public List<GameDto> getGames() {
		return StaticData.games;
	}

	@Override
	public boolean createGame(PlayerDto creator, String gameName, List<MountainDto> mountainDtos) {
		GameDto gameDto = new GameDto(creator, gameName, mountainDtos);
		gameDto.players.add(creator);
		StaticData.games.add(gameDto);
		
		creator.setup();
		
		return true;
	}

	@Override
	public GameDto joinGame(PlayerDto joinPlayer, String gameName) {
		GameDto joinedGameDto = null; 
		for (GameDto gameDto : StaticData.games) {
			if (gameName.equals(gameDto.name)) {
				joinedGameDto = gameDto;
				break;
			}
		}
		
		joinPlayer.setup();
		
		joinedGameDto.players.add(joinPlayer);
		joinedGameDto.inProgress = true;
		
		return joinedGameDto;
	}

	@Override
	public boolean deleteGame(PlayerDto player, String gameName) {
		for (GameDto gameDto : StaticData.games) {
			if (player.equals(gameDto.creator) && gameName.equals(gameDto.name)) {
				StaticData.games.remove(gameDto);
				return true;
			}
		}
		
		return false;
	}
}
